import axios from "axios";
import 'element-plus/es/components/message/style/css'
import { ElMessage } from 'element-plus'
import { useUserStore } from "@/stores/user";
import router from "@/router";

//创建实例
const httpInstance = axios.create(
    {
        baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
        timeout: 5000
    }
)
//设置拦截器
httpInstance.interceptors.request.use(config => {
    const userStore = useUserStore()
    const token = userStore.userInfo.token
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
}, error => Promise.reject(error))
httpInstance.interceptors.response.use(res => res, e => {
    const userStore = useUserStore()
    
    //统一错误处理
    ElMessage({ type: 'warning', message: e.response.data.message })
    //token失效401处理
    if (e.response.status === 401) {
        //清除数据
        userStore.clearUserInfo()
        //跳转到登录页
        router.push('/login')//注意此处不能用useRouter，需要直接导入router
    }
    return Promise.reject(e);
})

export default httpInstance